import 'package:dio/dio.dart';
import 'package:xiaomishop/app/net/Url.dart';

class HttManager {
  late Dio dio;
  static HttManager instance = HttManager._internal();

  ///工厂构造函数与普通构造函数的区别在于，
  ///工厂构造函数可以自定义实例的创建过程，并根据需要返回一个新的对象或现有的对象。
  ///这种灵活性使得我们能够在构造函数中执行一些逻辑，而不是简单地返回新创建的对象。
  factory HttManager() {
    return instance;
  }

  HttManager._internal() {
    print('构造函数。。。。。。。。。。。。。。');
    dio = Dio();
    dio.options.baseUrl = Url.BASE_URL;
    dio.options.connectTimeout = 8000;
    dio.interceptors.add(InterceptorsWrapper(onRequest:
        (RequestOptions requestOptions, RequestInterceptorHandler handler) {
      print('Request URL: ${requestOptions.uri}');
      print('Request Method: ${requestOptions.method}');
      print('Request Headers: ${requestOptions.headers}');
      print('Request Parameters: ${requestOptions.queryParameters}');
      print('Request Data: ${requestOptions.data}');
      // 在发送请求之前执行的逻辑
      // 修改请求头或请求参数等
      return handler.next(requestOptions); // 继续发送请求
    }, onResponse: (Response response, ResponseInterceptorHandler handler) {
      // 在接收到响应之后执行的逻辑
      // 修改响应数据等
      print('Response Status Code: ${response.statusCode}');
      print('Response Headers: ${response.headers}');
      print('Response Data: ${response.data}');
      return handler.next(response); // 继续处理响应
    }, onError: (DioError error, ErrorInterceptorHandler handler) {
      // 在请求过程中发生错误时执行的逻辑
      // 处理错误、重试请求等
      print('onError ${error.message}');
      return handler.next(error);
    }));
  }

  /// get请求
  Future<Response?> get(String url, {Map<String, dynamic>? map}) async {
    try {
      var result = await dio.get(url, queryParameters: map);
      return result;
    } catch (e) {
      print('HttManager get e $e }');
      return null;
    }
  }

  ///post请求
  Future<Response?> post(String url, Map<String, dynamic>? map) async {
    try {
      var result = await dio.post(url, queryParameters: map);
      return result;
    } catch (e) {
      print('HttManager post e $e }');
      return null;
    }
  }

  String urlFormat(String? url) {
    if (url == null) {
      return "";
    }
    String finalUrl = "${Url.BASE_URL}${url?.replaceAll("\\", "/")}";
    return finalUrl;
  }
}
